const express = require('express')
const router = express.Router()
const md5 = require('md5')
const userModel = require('../models/userModel')
const {data} = require("express-session/session/cookie");

router.get('/reg', (req, res) => {
    res.render('reg')
})

router.post('/reg', async (req, res) => {
    try {
        let {username} = req.body
        const p1 = await userModel.findOne({username})
        if (!p1) {
            const p = await userModel.create({
                ...req.body,
                password: md5(req.body.password)
            })
            res.render('success', {msg: '注册成功', url: '/login'})
        } else {
            return res.send('用户名已被注册')
        }
    } catch (err) {
        res.status(500)
        res.send('注册失败')
        return
    }

})
router.get('/login', (req, res) => {
    res.render('login')
})

router.post('/login', async (req, res) => {
    try {
        let {username, password} = req.body
        const p = await userModel.findOne({username, password: md5(password)})
        if (p) {
            req.session.username = p.username
            req.session.password = p.password
            res.render('success', {msg: '登录成功', url: '/account'})

        } else {
            return res.send('账号或密码错误')
        }
        res.render('success', {msg: '登录成功', url: '/account'})
    } catch (err) {
        res.status(500)
        res.send('注册失败')
        return
    }

})
router.post('/logout', (req, res) => {
    req.session.destroy(() => {
        res.render('success', {msg: '退出成功', url: '/login'})
    })
})
module.exports = router